/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller;

import entities.Applicant;
import java.util.List;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import persistence.GenericDAO;
import persistence.GenericDAOImpl;
import util.EmailSender;
import util.PasswordGenerator;

/**
 *
 * @author akefeli
 */
@Stateless
@LocalBean
public class RegistrationControllerEJB {

    // Add business logic below. (Right-click in editor and choose
    // "Insert Code > Add Business Method")
    public void register(String email, String firstName, String lastName){
        System.out.println(email+" is registered");
        String password = PasswordGenerator.generate();
        Applicant app = new Applicant();
        app.setPassword(password);
        app.setEmail(email);
        app.setFirstName(firstName);
        app.setLastName(lastName);
        GenericDAO<Applicant, Long> dao = new GenericDAOImpl(Applicant.class);
        dao.create(app);
        
        String subject = "Your new password for Online MUM Compro Application";
        String body = "Your new password is: " + password;
        EmailSender sender = new EmailSender("admin@gmail.com", email, subject, body);
        sender.send();
    }

    public boolean changePw(String email, String oldPw, String newPw) throws Exception {
        boolean result = false;
        GenericDAO<Applicant, Long> dao = new GenericDAOImpl(Applicant.class);
        List<Applicant> apps = dao.findAll();
        for(Applicant app:apps){
            if(app.getEmail().equals(email) && app.getPassword().equals(oldPw)){
                app.setPassword(newPw);
                dao.update(app);
                result = true;
                break;
            }
        }
        return result;
    }
    
}
